﻿#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;

public class UnityEmptyFolderClean 
{
	[MenuItem("Zhan/Clear Empty folders")]
	public static void Clean ()
	{
		//string path = Application.dataPath;
		//path = path.Substring(0, path.Length - "/Assets".Length);
		Clean(new DirectoryInfo(Application.dataPath));
        AssetDatabase.Refresh();
    }

	static bool Clean (DirectoryInfo folder)
	{
		//Debug.Log(folder.FullName);

		bool clear = true;

		foreach(FileSystemInfo info in folder.GetFileSystemInfos())
		{
			if (info is DirectoryInfo)
			{
				// 文件处理
				if (!Clean(info as DirectoryInfo))
				{
					clear = false;
				}
			}
			else
			{
				string filePath = info.FullName;
				// for mac
				if (filePath.EndsWith(".DS_Store"))
				{
					// nothing
				}
				else if (filePath.EndsWith(".meta"))
				{
					string metaOrigin = filePath.Substring(0, filePath.Length - ".meta".Length);
					// meta原文件存在
					if (File.Exists(metaOrigin))
					{
						clear = false;
					}
					// 空meta清理
					else if (!Directory.Exists(metaOrigin))
					{
						info.Delete();
					}
				}
				else
				{
					clear = false;
				}
			}
		}

		if (clear)
		{
			if (File.Exists(folder.FullName + "/.DS_Store"))
			{
				File.Delete(folder.FullName + "/.DS_Store");
			}

			folder.Delete();
            File.Delete(folder.FullName + ".meta");
            GameDebug.LogError($"清理文件夹:{folder.FullName}");            
        }

        return clear;
	}
	
	[MenuItem("Zhan/Clear Persistence Dir")]
	public static void ClearPersistenceDir ()
	{
		//DirectoryInfo dir = new DirectoryInfo(Application.persistentDataPath);
		DirectoryInfo dir = new DirectoryInfo(Application.persistentDataPath);
		if (dir.Exists)
		{
			DirectoryInfo[] childs = dir.GetDirectories();
			foreach (DirectoryInfo child in childs)
			{
				child.Delete(true);
			}
			dir.Delete(true);
		}
	}

}
#endif
